<%--
  Created by IntelliJ IDEA.
  User: xiepx
  Date: 2017/3/28
  Time: 16:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<%@ taglib prefix="ta" tagdir="/WEB-INF/tags/tatags" %>
<html>
<head>
    <title>通知发送</title>
    <%@ include file="/ta/inc.jsp" %>

    <script type="text/javascript" charset="utf-8"
            src="<%=basePath%>ta/resource/face1.0.0/lib/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8"
            src="<%=basePath%>ta/resource/face1.0.0/lib/ueditor/ueditor.all.min.js"></script>
</head>
<body class="no-scrollbar">
<ta:box fit="true">


    <ta:box fit="true" layout="border" layoutCfg="{leftWidth:400}">
        <ta:box fit="true" position="left">
            <ta:box id="sendUserBox" key="当前用户信息">
                <ta:text id="curSys" key="发送方系统" labelWidth="80" display="false"></ta:text>
                <ta:text id="curUserId" key="发送方编号" labelWidth="80" display="false"></ta:text>
                <ta:text id="curName" key="发送方姓名" labelWidth="80" display="false"></ta:text>
                <ta:text id="curOrgId" key="发送方组织" labelWidth="80" display="false"></ta:text>
                <ta:text id="curPositionId" key="发送方岗位" labelWidth="80" display="false"></ta:text>
            </ta:box>
            <ta:panel id="messageUserBox" key="消息接收人员" fit="true">
                <ta:box id="userQuery" cols="1">

                    <%--            <ta:box cols="2">
                                    <ta:selectInput id="sysid" key="目标系统" labelWidth="80" columnWidth="0.8" required="true"></ta:selectInput>

                                </ta:box>--%>
                    <ta:box cols="2">
                            <ta:selectTree columnWidth="0.75" fontCss="fnSetFont" url="WebController!webQueryAsyncOrgTree.do"  asyncParam="['orgid']"
                                           key="组织" labelWidth="80"  nameKey="orgname"
                                           idKey="orgid" parentKey="porgid" targetDESC="orgName"
                                           treeId="orgTree" targetId="orgId" />
                            <ta:box columnWidth="0.25">
                                <ta:checkboxgroup  id="isIncludeSun">
                                    <ta:checkbox checked="true" key="包含子组织" value="0"   />
                                </ta:checkboxgroup>
                            </ta:box>

                            <ta:text id="name" key="人员姓名" labelWidth="80" columnWidth="0.75"></ta:text>
                            <ta:buttonLayout columnWidth="0.25" align="left">
                                    <ta:button id="btnQuery" key="查询[Q]" hotKey="CTRL+Q" columnWidth="0.25"  isok="true"
                                        onClick="fnQueryMessageUser()"></ta:button>
                            </ta:buttonLayout>
                    </ta:box>

                </ta:box>
                <ta:box fit="true">
                    <ta:datagrid id="userGd" fit="true" selectType="checkbox" haveSn="true" forceFitColumns="true">
                        <ta:datagridItem id="userId" asKey="true" key="ID" hiddenColumn="true"/>
                        <ta:datagridItem id="tel" asKey="true" key="TEL" hiddenColumn="true"/>
                        <ta:datagridItem id="email" asKey="true" key="EMAIL" hiddenColumn="true"/>
                        <ta:datagridItem id="weChat" asKey="true" key="WECHAT" hiddenColumn="true"/>
                        <ta:datagridItem id="phoneApp" asKey="true" key="PHONEAPP" hiddenColumn="true"/>
                        <ta:datagridItem id="imId" asKey="true" key="IMID" hiddenColumn="true"/>
                        <ta:datagridItem id="loginId" asKey="true" key="人员账号" align="center"/>
                        <ta:datagridItem id="name" asKey="true" key="人员姓名" showDetailed="true" align="center" dataAlign="center"/>
                        <ta:dataGridToolPaging url="WebController!queryMessageUser.do" submitIds="userQuery"/>
                    </ta:datagrid>
                </ta:box>
            </ta:panel>
        </ta:box>

        <ta:box fit="true" position="center" cssStyle="padding:0px 10px;">
            <ta:panel id="mypanel" key="消息" fit="true" withButtonBar="true">
                <ta:text id="msgtitle" key="标题" labelWidth="60" required="true"/>
                <ta:checkboxgroup id="msgtype" key="渠道" labelWidth="60" collection="SENDMODE" required="true"
                                  cols="9"></ta:checkboxgroup>
                <ta:box fit="true">
                     <script id="editor" type="text/plain" style="height:80%;width:99.8%;" ></script>
                </ta:box>

                <ta:panelButtonBar align="right">
                    <ta:button key="发送[S]" id="sendtb" hotKey="Ctrl+S" isok="true" onClick="sendMg()"/>
                    <ta:button key="清空[C]" id="cleartb" hotKey="Ctrl+C" onClick="clearUeditor()"/>
                </ta:panelButtonBar>
            </ta:panel>
        </ta:box>
    </ta:box>
</ta:box>
<ta:boxComponent height="200px" width="400px" id="b2" arrowPosition="vertical">
	<ta:datagrid id="wxgrid" fit="true" haveSn="true" border="true" selectType="radio">
		<ta:datagridItem id="id" key="id" hiddenColumn="true"/>
		<ta:datagridItem id="name" key="公众号名称" />
		<ta:datagridItem id="appid" key="appid" sortable="true"/>
		<ta:datagridItem id="secret" key="secret" hiddenColumn="true"/>
		<ta:datagridItem id="defaultwx" key="默认公众号" collection="YESORNO" />
	</ta:datagrid>
</ta:boxComponent>
<ta:boxComponent height="200px" width="400px" id="b1" arrowPosition="vertical">
	<ta:datagrid id="sysgrid" fit="true" haveSn="true" border="true" selectType="checkbox">
		<ta:datagridItem id="id" key="id" hiddenColumn="true"/>
		<ta:datagridItem id="systemid" key="系统id" />
		<ta:datagridItem id="systemname" key="系统名称" />
	</ta:datagrid>
</ta:boxComponent>
</body>
<script type="text/javascript">
    $(document).ready(function () {
        $("body").taLayout();

        //实例化编辑器
        //建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
        var option = {
            autoHeightEnabled: false,//是否自动长高，默认true
            elementPathEnabled :false,//是否启用元素路径，默认是显示
            autoFloatEnabled: true,//是否保持toolbar的位置不动，默认true
            wordCount: true,//是否开启字数统计,默认 true
            maximumWords:10000,//允许的最大字符数,默认10000
        };
        ue = UE.getEditor('editor', option);

        /*
         var options={};
         options.instance1=1;
         options.width=300;
         options.columns=4;
         options.digit=2;
         options.beforeSubmit=useridChange;
         options.callBackFun=fn_setUser;
         options.url="/message/messageSend!getSuggest_user.do";
         var $input = $("#name");
         if (typeof require == "function"){
         require(["suggest"],function(){
         me = new TaSuggest($input,options);
         me.suggest();
         });
         }else{
         me = new TaSuggest($input,options);
         me.suggest();
         }*/
         $("#check_2_msgtype").parent().on("click",function(){
         	if(Base.getValue("check_2_msgtype")=='2'){
         		var target=event.srcElement?event.srcElement:event.target;
				Base.showBoxComponent("b2",target);
				Base.submit("","../wxRegister/wxRegisterController!queryWx.do");
         	}
		 });
		 $("#check_0_msgtype").parent().on("click",function(){
         	if(Base.getValue("check_0_msgtype")=='0'){
         		var target=event.srcElement?event.srcElement:event.target;
				Base.showBoxComponent("b1",target);
				Base.submit("","../sysAppManage/getSysList.do");
         	}
		 });
		 $("#b1,#b2").css("z-index","1000");
    });
	
    //suggest 查询结果选择回调
    /*function fn_setUser(g_Suggest) {
     if (g_Suggest != "") {
     Base.setValue("t_logonname", g_Suggest[0]);
     Base.setValue("t_username", g_Suggest[1]);
     Base.setValue("t_userorgid", g_Suggest[3]);
     Base.setValue("t_userid", g_Suggest[4]);
     var rowData_new = new Array();
     var rowData = gridData;
     var userid = g_Suggest[0];
     for (var i = 0; i < rowData.length; i ++ ) {
     if(rowData[i].loginid==userid){
     rowData_new.push(rowData[i]);
     }
     }
     Base._setGridData("userGd",rowData_new);
     }
     }*/

    //单人更改设置选中后的样式
    function fnSetFont(treeId, treeNode){
        if (treeNode.effective == 0) return {'text-decoration':'line-through'};
        if (!treeNode.admin) return {'color': 'red'};
        return {};
    }

    //查询可接受消息人员信息
    function fnQueryMessageUser() {
        Base.submit("userQuery", "WebController!queryMessageUser.do", {}, null, null, null, null);
    }

    //发送消息
    function sendMg() {
        //构造发送方信息
        var sendUser = getSendUser();
        if(!sendUser)return;

        //构造接受方信息
        var rUsers = getReciveUsers();
        if(!rUsers)return;

        //构造消息信息
        var message = getMessage();
        if(!message)return;

		//构造微信号数据
		var wechat = null;
		if(contains(message.messageTypes,"2")){
			wechat = getWechat();
			if(!wechat)return;
		}
		
        var data  ={
            "msgjsonstr" : JSON.stringify({
                "user": sendUser,
                "userlist" : rUsers,
                "message" : message,
                "wechat" : wechat
            }),
            "file" : JSON.stringify(getFiles())
        };


        $.ajax({
            type: "post",
            url : "<%=basePath%>/messageHttp/messageHttpController!sendMessageWithMap.do",
            data :data,
            contentType:"application/x-www-form-urlencoded;charset=utf-8",
            success : mgSucc
        })
    }

    //消息发送成功回调
    function mgSucc(data) {
        ue.setContent('');
        Base.setValue("msgtype", []);
        Base.setValue("msgtitle", '');
        if(data){
        	var json = JSON.parse(data);
        	if(json.state =="1"){
        		 Base.alert("已发送","success");;
        	}else{
        		 Base.alert("发送异常--"+json.message,"error");;
        	}
        }else{
        	 Base.alert("服务器无响应","warn");;
        }
    }

    //getSendUser
    function getSendUser(){
        var curUserId =  Base.getValue("curUserId");
        var curName = Base.getValue("curName");
        var curSys = Base.getValue("curSys");
        if(typeof curUserId == undefined || curUserId == "" ||
            typeof curName == undefined || curName == "" ||
            typeof curSys == undefined || curSys == ""
        ){
            Base.alert("发送方信息缺失");
            return false;
        }

        return {
            userId : curUserId,
            name : curName,
            appId : curSys
        }
    }
    //getReciveUsers
    function getReciveUsers(){
        var rowData = Base.getGridSelectedRows("userGd");
        if(rowData.length < 1){
            Base.alert("无人员可发送通知");
            return false;
        }
        var sysRowData = Base.getGridSelectedRows("sysgrid");
        
        var ruserlist = [];
        for(var j = 0; j < sysRowData.length; j++){
        	for (var i = 0; i < rowData.length; i++) {
            	var ruser = {
                	appId : sysRowData[j].systemid,
                	userId : rowData[i].userId,
                	name : rowData[i].name,
                	tel : rowData[i].tel,
                	email : rowData[i].email,
                	weChat : rowData[i].weChat,
                	phoneApp : rowData[i].phoneApp,
                	imId : rowData[i].imId
            	}
            	ruserlist.push(ruser);
        	}
        }
        if(sysRowData.length < 1){
           for (var i = 0; i < rowData.length; i++) {
            	var ruser = {
                	appId : Base.getValue("curSys"),
                	userId : rowData[i].userId,
                	name : rowData[i].name,
                	tel : rowData[i].tel,
                	email : rowData[i].email,
                	weChat : rowData[i].weChat,
                	phoneApp : rowData[i].phoneApp,
                	imId : rowData[i].imId
            	}
            	ruserlist.push(ruser);
        	}
        }
        
        return ruserlist;
    }
    //getMessage
    function getMessage(){
        var mgHead = Base.getValue("msgtitle");
        var mgType = Base.getValue("msgtype");
        var mgContent = ue.getContent();
        var mgText = ue.getContentTxt();
        if (typeof mgHead == undefined || mgHead == "" ||
                    typeof mgType == undefined || mgType == "" || mgType == []
                        || !ue.hasContents()) {
            Base.alert("通知内容不完整，请核实消息标题、渠道、内容等信息");
            return false;
        }

        return {
            title : mgHead,
            messageTypes : mgType,
            content : mgContent,
            text : mgText,
            toAlluser : false,
            scriptMethod :"messageDwr"
        };
    }
    //获取文件信息
    function getFiles(){
        //获取文件信息
        var a_hrefs = ue.body.getElementsByTagName('a');
        var files = [];
        for (var i = 0; i < a_hrefs.length; i++) {    //直接获取路径
//             files[a_hrefs[i].title] = a_hrefs[i].href;
			var f = {};
			f.name = a_hrefs[i].title;
			f.path = a_hrefs[i].href;
			files[i]=f;
        }
        return files;
    }
    //getWechat
    function getWechat(){
    	var rows = Base.getGridSelectedRows("wxgrid");
    	if(rows.length == 0){
    		rows[0] = getDefaultWx();
    	}
    	var wx = {
                appid : rows[0].appid,
                secret : rows[0].secret,
                name : rows[0].name,
                toAlluser : false
        }
    	return wx;
    }
    function getDefaultWx(){
    	var data = Base.getGridData("wxgrid");
    	for(var i=0;i<data.length;i++){
    		if(data[i].defaultwx == '1'){
    				return data[i];
    		}
    	}
    }
    function clearUserQuery() {
        Base.clearData("userQuery");
        Base.clearGridData("userGd");
    }
    function clearUeditor() {
        ue.setContent('');
        Base.setValue("msgtitle", '');
    }
    function contains(arr, obj) {  
    	var i = arr.length;  
    	while (i--) {  
        	if (arr[i] === obj) {  
            	return true;  
        	}  
    	}  
    	return false;  
	}  
</script>
</html>
